package com.derbysoft.synxisadapter.action.settings.hotel;

import com.derbysoft.synxisadapter.action.BaseAdapterAction;
import com.derbysoft.synxisadapter.commons.model.Hotel;
import com.derbysoft.synxisadapter.commons.repository.HotelRepository;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * User: jason
 * Date: 2012-11-14
 */
@Results(value = {
        @Result(name = ImportAction.IMPORT_VIEW, location = "/page/settings/hotel/Import.ftl")
})
public class ImportAction extends BaseAdapterAction {
    private static Log logger = LogFactory.getLog(ImportAction.class);
    public static final String IMPORT_VIEW = "import";
    private static final long serialVersionUID = 572146812454l;
    public static final String SYNXIS = "SYNXIS";

    private File sourceFile;
    private String sourceFileContentType;
    private String sourceFileFileName;

    @Autowired
    private HotelRepository hotelRepository;

    private String result;

    @Action("importView")
    public String importView() {
        return IMPORT_VIEW;
    }

    @Action("batchImport")
    public String batchImport() {
        File targetFile = new File(ServletActionContext.getServletContext().getRealPath("/upload") + File.separatorChar + sourceFileFileName);
        List<Hotel> hotelList = new ArrayList<Hotel>();
        StringBuilder builder = new StringBuilder();
        int count = 0;
        try {
            FileUtils.copyFile(sourceFile, targetFile);
            LineIterator lineIterator = IOUtils.lineIterator(new FileInputStream(targetFile), "UTF-8");
            while (lineIterator.hasNext()) {
                count++;
                String line = lineIterator.nextLine();
                String[] fields = StringUtils.split(line, "|");
                if (fields == null || fields.length != 3) {
                    builder.append(count).append(":").append("[invalid line ], ").append(line).append("<br>");
                    continue;
                }
                if (!Pattern.compile("[0-9]+").matcher(fields[0]).matches()) {
                    builder.append(count).append(":").append("[invalid number ], ").append(line).append("<br>");
                    continue;
                }
                if (hotelRepository.findById(fields[0]) != null) {
                    builder.append(count).append(":").append(String.format("[ this hotel existed ] :%s  ", fields[0])).append("<br>");
                    continue;
                }
                Hotel hotel = new Hotel();
                hotel.setId(fields[0]);
                hotel.setName(fields[1]);
                hotel.setPassport(fields[2]);
                hotel.setProviderPassport(SYNXIS);
                hotel.setProviderName(SYNXIS);
                hotel.setStatus(Hotel.Status.ENABLED);
                hotelList.add(hotel);
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        hotelRepository.saveAll(hotelList);
        builder.append(String.format(" TotalLines: [%d],  Successful: [%d]", count, hotelList.size()));
        result = builder.toString();
        return IMPORT_VIEW;
    }

    public File getSourceFile() {
        return sourceFile;
    }

    public void setSourceFile(File sourceFile) {
        this.sourceFile = sourceFile;
    }

    public String getSourceFileContentType() {
        return sourceFileContentType;
    }

    public void setSourceFileContentType(String sourceFileContentType) {
        this.sourceFileContentType = sourceFileContentType;
    }

    public String getSourceFileFileName() {
        return sourceFileFileName;
    }

    public void setSourceFileFileName(String sourceFileFileName) {
        this.sourceFileFileName = sourceFileFileName;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }
}
